package com.ruoyi.system.service.impl;

import java.util.List;

import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ExamManagementMapper;
import com.ruoyi.system.domain.ExamManagement;
import com.ruoyi.system.service.IExamManagementService;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.system.service.IScoreManagementService;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.ruoyi.system.domain.dto.StatisticsDTO;
import com.ruoyi.system.domain.dto.StatisticsDTO.PositionData;

import javax.validation.Validator;

/**
 * 四级联考成绩录入Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-02
 */
@Service
public class ExamManagementServiceImpl implements IExamManagementService 
{
    private static final Logger log = LoggerFactory.getLogger(ExamManagementServiceImpl.class);

    @Autowired
    private ExamManagementMapper examManagementMapper;
    
    @Autowired
    protected Validator validator;
    
    @Autowired
    private IScoreManagementService scoreManagementService;
    @Autowired
    private ISysConfigService configService;

    /**
     * 查询四级联考成绩录入
     * 
     * @param id 四级联考成绩录入主键
     * @return 四级联考成绩录入
     */
    @Override
    public ExamManagement selectExamManagementById(Long id)
    {
        return examManagementMapper.selectExamManagementById(id);
    }

    /**
     * 查询四级联考成绩录入列表
     * 
     * @param examManagement 四级联考成绩录入
     * @return 四级联考成绩录入
     */
    @Override
    public List<ExamManagement> selectExamManagementList(ExamManagement examManagement)
    {
        return examManagementMapper.selectExamManagementList(examManagement);
    }

    /**
     * 新增四级联考成绩录入
     * 
     * @param examManagement 四级联考成绩录入
     * @return 结果
     */
    @Override
    public int insertExamManagement(ExamManagement examManagement)
    {
        return examManagementMapper.insertExamManagement(examManagement);
    }

    /**
     * 修改四级联考成绩录入
     * 
     * @param examManagement 四级联考成绩录入
     * @return 结果
     */
    @Override
    public int updateExamManagement(ExamManagement examManagement)
    {
        return examManagementMapper.updateExamManagement(examManagement);
    }

    /**
     * 批量删除四级联考成绩录入
     * 
     * @param ids 需要删除的四级联考成绩录入主键
     * @return 结果
     */
    @Override
    public int deleteExamManagementByIds(Long[] ids)
    {
        return examManagementMapper.deleteExamManagementByIds(ids);
    }

    /**
     * 删除四级联考成绩录入信息
     * 
     * @param id 四级联考成绩录入主键
     * @return 结果
     */
    @Override
    public int deleteExamManagementById(Long id)
    {
        return examManagementMapper.deleteExamManagementById(id);
    }

    /**
     * 导入四级联考成绩数据
     * 
     * @param examList 成绩数据列表
     * @param updateSupport 是否更新支持，如果已存在，是否覆盖
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importExamData(List<ExamManagement> examList, boolean updateSupport, String operName)
    {
        if (StringUtils.isNull(examList) || examList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        for (ExamManagement exam : examList)
        {
            try
            {
                // 验证是否存在相同的准考证号或身份证号
                ExamManagement existExam = new ExamManagement();
                if (StringUtils.isNotEmpty(exam.getExamNumber()))
                {
                    existExam.setExamNumber(exam.getExamNumber());
                }
                else if (StringUtils.isNotEmpty(exam.getIdCard()))
                {
                    existExam.setIdCard(exam.getIdCard());
                }
                else
                {
                    throw new ServiceException("导入数据中准考证号和身份证号不能同时为空");
                }
                
                List<ExamManagement> existList = examManagementMapper.selectExamManagementList(existExam);
                
                if (StringUtils.isNull(existList) || existList.size() == 0)
                {
//                    // 计算总成绩，如果需要的话
//                    if (exam.getAdministrativeAptitudeScore() != null
//                            && exam.getEssayScore() != null
//                            && exam.getProfessionalSubjectScore() != null)
//                    {
//                        // 计算总成绩，此处仅为示例，根据实际需要调整计算方式
//                        exam.setTotalScore(
//                            exam.getAdministrativeAptitudeScore()
//                            .add(exam.getEssayScore())
//                            .add(exam.getProfessionalSubjectScore())
//                        );
//                    }
                    
                    // 如果不存在，执行插入操作
                    examManagementMapper.insertExamManagement(exam);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、准考证号 " + exam.getExamNumber() + " 导入成功");
                }
                else if (updateSupport)
                {
                    // 如果存在且允许更新
                    exam.setId(existList.get(0).getId()); // 设置ID，确保更新正确的记录
                    
//                    // 计算总成绩，如果需要的话
//                    if (exam.getAdministrativeAptitudeScore() != null
//                            && exam.getEssayScore() != null
//                            && exam.getProfessionalSubjectScore() != null)
//                    {
//                        // 计算总成绩，此处仅为示例，根据实际需要调整计算方式
//                        exam.setTotalScore(
//                            exam.getAdministrativeAptitudeScore()
//                            .add(exam.getEssayScore())
//                            .add(exam.getProfessionalSubjectScore())
//                        );
//                    }
                    
                    examManagementMapper.updateExamManagement(exam);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、准考证号 " + exam.getExamNumber() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、准考证号 " + exam.getExamNumber() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、准考证号 " + exam.getExamNumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 生成合格成绩名单
     * 筛选条件：专业科目成绩>=50且总成绩>=50
     * 
     * @param operName 操作用户
     * @return 合格人数
     */
    @Override
    @Transactional
    public int generateQualifiedScoreList(String operName)
    {
        String sjysZykmcj = configService.selectConfigByKey("sys.sjys.zykmcj");
        String sjyxZykmcj = configService.selectConfigByKey("sys.sjyx.zykmcj");

        String sjysZcj = configService.selectConfigByKey("sys.sjys.zcj");
        String sjyxZcj = configService.selectConfigByKey("sys.sjyx.zcj");

        String sjysZyjncscj = configService.selectConfigByKey("sys.sjys.zyjncscj");
        String sjyxZyjncscj = configService.selectConfigByKey("sys.sjyx.zyjncscj");



        // 创建查询条件对象
        ExamManagement criteria = new ExamManagement();
        
        // 查询所有考生信息
        List<ExamManagement> allExamList = examManagementMapper.selectExamManagementList(criteria);
        
        // 创建合格考生列表
        List<ExamManagement> qualifiedList = new java.util.ArrayList<>();
        
        // 遍历考生信息，筛选出符合条件的考生并更新为合格
        for (ExamManagement exam : allExamList)
        {
            if (exam.getLeibie() !=null && exam.getLeibie().equals("市级以上")) {
                // 检查专业科目成绩和总成绩是否都大于等于50
                if (exam.getProfessionalSubjectScore() != null
                        && exam.getTotalScore() != null
                        && exam.getProfessionalSubjectScore().compareTo(new java.math.BigDecimal(sjysZykmcj)) >= 0
                        && exam.getTotalScore().compareTo(new java.math.BigDecimal(sjysZcj)) >= 0)
                {
                    if (exam.getHasProfessionalSkillTest() != null && exam.getHasProfessionalSkillTest().equals("是")
                        && exam.getProfessionalSkillTestScore() != null && exam.getProfessionalSkillTestScore().compareTo(new java.math.BigDecimal(sjysZyjncscj)) >= 0) {
                        // 设置为合格
//                        exam.setFinalResult("通过");

                        // 更新数据库记录
                        examManagementMapper.updateExamManagement(exam);

                        // 添加到合格名单
                        qualifiedList.add(exam);
                    }

                    if (exam.getHasProfessionalSkillTest() == null ||exam.getHasProfessionalSkillTest().equals("") ||exam.getHasProfessionalSkillTest().equals("否")) {
                        // 设置为合格
//                        exam.setFinalResult("通过");

                        // 更新数据库记录
                        examManagementMapper.updateExamManagement(exam);

                        // 添加到合格名单
                        qualifiedList.add(exam);
                    }

                }
            }
            if (exam.getLeibie() ==null || !exam.getLeibie().equals("市级以上")) {
                // 检查专业科目成绩和总成绩是否都大于等于50
                if (exam.getProfessionalSubjectScore() != null
                        && exam.getTotalScore() != null
                        && exam.getProfessionalSubjectScore().compareTo(new java.math.BigDecimal(sjyxZykmcj)) >= 0
                        && exam.getTotalScore().compareTo(new java.math.BigDecimal(sjyxZcj)) >= 0)
                {
                    if (exam.getHasProfessionalSkillTest() != null && exam.getHasProfessionalSkillTest().equals("是")
                            && exam.getProfessionalSkillTestScore() != null && exam.getProfessionalSkillTestScore().compareTo(new java.math.BigDecimal(sjyxZyjncscj)) >= 0) {
                        // 设置为合格
//                        exam.setFinalResult("通过");

                        // 更新数据库记录
                        examManagementMapper.updateExamManagement(exam);

                        // 添加到合格名单
                        qualifiedList.add(exam);
                    }

                    if (exam.getHasProfessionalSkillTest() == null ||exam.getHasProfessionalSkillTest().equals("") ||exam.getHasProfessionalSkillTest().equals("否")) {
                        // 设置为合格
//                        exam.setFinalResult("通过");

                        // 更新数据库记录
                        examManagementMapper.updateExamManagement(exam);

                        // 添加到合格名单
                        qualifiedList.add(exam);
                    }

                }
            }

        }
        
        // 将合格考生插入到成绩合格名单
        int qualifiedCount = 0;
        if (qualifiedList.size() > 0) {
            qualifiedCount = scoreManagementService.insertQualifiedScoreListFromExam(qualifiedList, operName);
        }
        
        return qualifiedCount;
    }

    /**
     * 获取四级联考成绩录入统计数据
     * 
     * @return 统计数据
     */
    @Override
    public StatisticsDTO getExamStatistics()
    {
        // 创建返回对象
        StatisticsDTO statisticsDTO = new StatisticsDTO();
        
        // 查询所有考试成绩数据
        List<ExamManagement> examList = examManagementMapper.selectExamManagementList(new ExamManagement());
        
        // 总数
        int total = examList.size();
        statisticsDTO.setTotal(total);
        
        // 通过和未通过数量（根据规则判断，如专业科目>=50且总成绩>=50）
        int passed = 0;
        // 职位分布统计
        Map<String, Integer> positionMap = new HashMap<>();
        
        for (ExamManagement exam : examList)
        {
            // 统计通过人数
            if (exam.getProfessionalSubjectScore().compareTo(new BigDecimal("50")) >= 0
                    && exam.getTotalScore().compareTo(new BigDecimal("50")) >= 0)
            {
                passed++;
            }
            
            // 统计职位分布
            String position = exam.getAppliedPosition();
            if (position != null && !position.isEmpty())
            {
                positionMap.put(position, positionMap.getOrDefault(position, 0) + 1);
            }
        }
        
        statisticsDTO.setPassed(passed);
        statisticsDTO.setFailed(total - passed);
        
        // 转换职位分布数据为前端所需格式
        List<PositionData> positionDataList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : positionMap.entrySet())
        {
            positionDataList.add(new PositionData(entry.getKey(), entry.getValue()));
        }
        statisticsDTO.setPositionData(positionDataList);
        
        return statisticsDTO;
    }
}
